﻿using Models;
using Views;
using System.Collections.Generic;
using System;

namespace Presenters
{
    /// <summary>
    /// Presenter for the Server Details page of the Add Databases Wizard
    /// </summary>
    public class ServerDetailsPresenter : PresenterBase<IServerDetailsView>
    {
        /// <summary>
        /// Initialise the Server Details page
        /// </summary>
        /// <param name="view">An instance that impliments IServerDetailsView</param>
        public ServerDetailsPresenter(IServerDetailsView view)
            : base(view)
        {
        }

        /// <summary>
        /// Clear all cached data for this presenter
        /// </summary>
        public void ClearCache()
        {
            m_UserInterface = null;
        }

        /// <summary>
        /// The user interface that we are currently using to collect the Server Details
        /// </summary>
        public SQPlugin.IServerDetails UserInterface
        {
            get
            {
                if (m_UserInterface == null)
                {
                    Services.ServersService serverService = new Services.ServersService(View.ServerPluginID);
                    m_UserInterface = serverService.GetServerDetailsUI();
                }

                return m_UserInterface;
            }
        }

        /// <summary>
        /// Validate the server details for the view
        /// </summary>
        /// <returns>True if everything is valid, otherwise false</returns>
        public bool ValidateServer()
        {
            // Assume validation is a success
            bool valid = true;

            Server server = UserInterface.GetServerDetails();

            Services.ServersService serverService = new Services.ServersService(View.ServerPluginID);

            // If we failed validation then display an error message to the user
            if (!serverService.ValidateServer(server))
            {
                ViewManager.ViewFactory.DisplayError("Please enter valid details for a Database Server connection and try again",
                                  "Database Server Details Error");

                valid = false;
            }

            return valid;
        }

        /// <summary>
        /// Get the server data out of the user interface
        /// </summary>
        /// <returns>A server object or null if there is an error</returns>
        public Models.Server GetData()
        {
            Models.Server result = null;

            if (UserInterface != null)
            {
                result = UserInterface.GetServerDetails();
            }

            return result;
        }

        /// <summary>
        /// Reference to the user interface we are using to get the server details
        /// </summary>
        private SQPlugin.IServerDetails m_UserInterface;
    }
}
